Understanding :nth-child() vs :nth-last-child() in CSS
The :nth-child() and :nth-last-child() pseudo-classes in CSS are used to select elements based on their position among siblings, but they count from opposite ends.
:nth-child(n) – Selects the nth child from the start (first child is 1).
:nth-last-child(n) – Selects the nth child from the end (last child is 1).
Both can use formulas like 2n, 2n+1, or 3n+2 for selecting patterns of elements.
In this example, :nth-child(2n) highlights items 2, 4, and 6 from the start with a light blue background. :nth-last-child(2n) makes items 2, 4, and 6 from the end bold, demonstrating the difference in counting direction.
Use :nth-child() when targeting elements from the beginning of the container.
Use :nth-last-child() when targeting elements from the end.
Combine with other pseudo-classes like :not() or :first-child for precise selections.
Test with dynamic content as adding/removing elements may affect which items are selected.